// 导入工具类函数
const utils = require('../../../utils/util');
let app = getApp()
const db = wx.cloud.database({
  env: app.globalData.CLOUD_ENV
})
const DBLibrary = db.collection('db_library');
let DBExam = db.collection('db_exam');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 题目类型
    array: ['单选题'],
    // 选择题目类型的索引
    index: 0,
    // 当前类型题目的数量
    total: 0,
    current: 0,
    formData: {
      lib_id: "", // 1.试卷ID
      type: '',
      text: '',
      e_question: "", // 题目 
      e_analysis: "", // 题目解析 
      e_options: "", // 题目选项 
      e_score: "", //8. 题目分值 
      e_answer: "", // 题目答案 
      library_name: "", // 试卷名称
      e_create_time: "", // 创建题目的时间
      e_code: "", // 如果有代码，就显示
    },
    idx: 1,
    library_name: "", //试卷名称
    lib_id: "", // 试卷id
    type: "", //  分类
    options: [{
        opt: '',
        content: '',
        id: 0
      },
      {
        opt: '',
        content: '',
        id: 1
      },
    ],
    lists: []
  },
  // 点击提交题目 （收集表单信息）
  addFormDataFunc() {
    let that = this;
    let formData = this.data.formData;
    let options = this.data.options;
    let openid = wx.getStorageSync('openid');
    formData['library_name'] = this.data.library_name;
    formData['lib_id'] = this.data.lib_id;
    formData['type'] = this.data.type;
    if (!openid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return false;
    }
    if (options) {
      formData['e_options'] = this.data.options;
    }
    if (formData['e_answer'] == '') {
      wx.showToast({
        title: '请输入题目答案',
        icon: 'none'
      })
      return false;
    }
    if (formData['lib_id'] == '') {
      wx.showToast({
        title: '请重新选择试卷再进入页面',
        icon: 'none'
      })
      return false;
    }
    if (formData['e_score'] == '') {
      wx.showToast({
        title: '请输入题目分值',
        icon: 'none'
      })
      return false;
    }
    if (formData['e_analysis'] == '') {
      wx.showToast({
        title: '请输入题目解析',
        icon: 'none'
      })
      return false;
    }
    if (formData['e_question'] == '') {
      wx.showToast({
        title: '请输入题目名称',
        icon: 'none'
      })
      return false;
    }
    // 设置创建题目的时间
    formData['e_create_time'] = utils.formatTime(new Date());
    formData['openid'] = openid;

    wx.showLoading({
      title: '正在添加题目...',
    })

    // 检测表单信息是否涉嫌违规
    wx.cloud.callFunction({
      // name: 是云函数名称
      name: 'msgsec',
      // data: 是提交给云函数的数据
      data: {
        content: JSON.stringify(formData),
        openid
      },
      // sucess: 表示符合请求的回调
      async success(res) {
        let {
          result: {
            errCode,
            errMsg
          }
        } = res;
        // console.log(res)
        if (errCode == 0) {
          // 把输入插入到题目表
          let obj = await DBExam.where({
            e_question: formData['e_question']
          }).count();
          if (obj.total == 0) {
            DBExam.add({
                data: formData
              })
              .then(
                content => {
                  if (content.errMsg == "collection.add:ok") {
                    wx.showToast({
                      title: '添加题目成功。',
                      icon: 'none'
                    })
                    that.getTopicList(formData['lib_id'])

                    formData['e_question'] = '';
                    formData['e_analysis'] = '';
                    formData['e_options'] = '';
                    formData['e_score'] = '';
                    formData['e_answer'] = '';
                    formData['e_code'] = '';
                    that.setData({
                      formData,
                      options: [{
                        opt: '',
                        content: '',
                        id: 0
                      },
                      {
                        opt: '',
                        content: '',
                        id: 1
                      },
                      ]
                    })
                    wx.hideLoading();
                  } else {
                    wx.showToast({
                      title: '添加题目失败。',
                      icon: 'error'
                    })
                    wx.hideLoading();
                  }
                }
              )
          } else {
            wx.showToast({
              title: '这道题重复了',
              icon: 'none'
            })
          }
        } else {
          if (errMsg != "openapi.security.msgSecCheck:ok") {
            wx.showToast({
              title: '您输入的内容包含敏感词哦。',
              icon: 'none'
            })
          } else {
            wx.showToast({
              title: `${errMsg},${errCode}`,
              icon: 'none'
            })
          }
        }
      },
      fail() {
        wx.showToast({
          title: '云服务发生异常。',
          icon: 'none'
        })
      }
    })
  },
  // 返回
  goBackTo() {
    wx.navigateTo({
      url: '../lib/lib',
    })
  },
  // 侦听输入框或输入域的变化
  addInputFunc(event) {
    // 获取表单信息（根据key获取）
    let key = event.currentTarget.dataset['key'];
    // 输入的值
    let v1 = event.detail.value;
    // 表单信息
    let formData = this.data.formData;
    // 利用对象key的唯一性储存数据
    formData[key] = v1;
    this.setData({
      formData
    })
  },
  // 处理题目选项
  addInputOptionFunc(event) {
    // console.log('--->',event)
    let num = event.currentTarget.dataset['num'];
    let tag = event.currentTarget.dataset['tag'];
    let options = this.data.options;
    let v1 = event.detail.value;
    // 选项  例如： A,B,C,D
    if (tag == "opt") {
      options[num].opt = v1;
    }
    // 选项内容： 例如： 否   /  是
    if (tag == "con") {
      options[num].content = v1;
    }
    // 设置options
    this.setData({
      options
    })
  },
  // 增加题目选项
  addTopicOptionFunc() {
    let idx = this.data.idx - 0;
    idx += 1
    let obj = {
      opt: '',
      content: '',
      id: idx
    };
    let arr = this.data.options;
    arr.push(obj);
    this.setData({
      options: arr,
      idx
    })
  },
  // 删除题目选项
  removeTopicOptionFunc(event) {
    let id = event.currentTarget.dataset.id;
    console.log({
      id
    })
    let arr = this.data.options.filter(item => {
      return item.id != id;
    })
    this.setData({
      options: arr
    })
  },
  // 获取该题库的该题型数量
  async addTopicTypeCount(lib_id) {
    // console.log({ lib_id })
    await DBExam.where({
        lib_id
      }).count().then(
        content => {
          if (content.errMsg == "collection.count:ok") {
            this.setData({
              current: content.total
            })
          }
        }
      )
      .catch(err => {
        console.log(err)
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let formData = {};
    if (options['lib_id'] == undefined || options['type'] == undefined || options['library_name' == undefined]) {
      return false;
    }
    // 初始化
    formData['lib_id'] = options['lib_id'];
    formData['type'] = options['type'];
    formData['library_name'] = options['library_name'];
    let {
      lib_id,
      type,
      library_name
    } = formData

    this.setData({
      lib_id,
      type,
      library_name
    })
    this.getTopicList(lib_id)
  },


  // 获取题目列表
  async getTopicList(lib_id) {
    let res = await DBExam.where({
      lib_id
    }).count()
    let count = res.total;
    let all = [];
    // wx.showLoading({
    //   title: '正在加载。。',
    // })
    for (let i = 0; i < count; i += 20) {
      await DBExam.where({
          lib_id
        }).skip(i).get()
        .then(
          content => {
            // console.log('1.0', content)
            let {
              data
            } = content;
            if (data.length != 0) {
              let arr = data.map(item => {
                let obj = {
                  ...item
                }
                return obj;
              })
              all = all.concat(arr)
            }
          }
        )
    }
    this.setData({
      lists: all
    })
    // wx.hideLoading();
  },

  // 删除
  removeFn(e) {
    let _id = e.currentTarget.dataset.id;
    let _openid = wx.getStorageSync('openid')
    if (_openid != app.globalData.OPENID ) {
      wx.showToast({
        title: '您没有权限删除题目。',
        icon: 'none'
      })
      return false;
    }
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除该题目吗?',
      complete: (res) => {
        if (res.cancel) {

        }
        if (res.confirm) {
          DBExam.doc(_id).remove().then(
            content => {
              console.log('content', content)
              let {
                errMsg
              } = content;
              if (errMsg == "document.remove:ok") {
                let arr = that.data.lists;
                let newArr = arr.filter(item => {
                  if (item._id != _id) {
                    return item
                  }
                })
                that.setData({
                  lists: newArr
                })
              } else {
                wx.showToast({
                  title: '删除题目失败。',
                  icon: 'none'
                })
              }
            }
          )
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 初始化数据
    // let formData = this.data.formData;
    // formData['e_question'] = '';
    // formData['e_analysis'] = '';
    // formData['e_options'] = '';
    // formData['e_score'] = '';
    // formData['e_answer'] = '';
    // this.setData({
    //   formData,
    //   idx: 1,
    //   options: [{
    //       opt: '',
    //       content: '',
    //       id: 0
    //     },
    //     {
    //       opt: '',
    //       content: '',
    //       id: 1
    //     },
    //   ]
    // })
    // // this.addTopicTypeCount(formData['lib_id']);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})